package com.example.outdoor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.example.outdoor.utils.Constants;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;

import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.os.StrictMode;


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class MainActivity extends Activity implements OnClickListener{

	//Property declaration
		Button btnLogin;
		TextView lblStatus;
		EditText txtUserName,txtPassword;
		SharedPreferences pref;
		SharedPreferences prefUserName;
		String mGetSavedData ="0";
		String UserName="";
		static ProgressBar progressBar1;
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getSharedPreferences("loginstatus", MODE_PRIVATE);
        mGetSavedData = pref.getString("savedData",mGetSavedData);
        if (mGetSavedData.equals("1")) {
        	 Intent our2Intent=new Intent(MainActivity.this,MenuPage.class);
			 startActivity(our2Intent);
			 finish();
		}
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        btnLogin=(Button)findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(this);
        lblStatus=(TextView)findViewById(R.id.lblStatus);
        txtUserName=(EditText)findViewById(R.id.txtUserName);
        txtPassword=(EditText)findViewById(R.id.txtPassword);
        progressBar1 = (ProgressBar) findViewById(R.id.progressBar1);
        progressBar1.setVisibility(View.GONE);
        addKeyListener();
    }
@Override
	public void onClick(View v) {
	
		switch(v.getId())
		{
			case R.id.btnLogin:
				click();
						break;
		}
	}
	public void click()
	{
		String userName=txtUserName.getText().toString();
		String password=txtPassword.getText().toString();
		
		
		if (txtUserName.getText().toString().equals("") ) {
			
			
			Toast.makeText(getApplicationContext(), "Please enter username...", Toast.LENGTH_LONG).show();
			
			return;
			
			
		}
		
		else     if (txtPassword.getText().toString().equals("") ) {
			
			
			Toast.makeText(getApplicationContext(), "Please enter password...", Toast.LENGTH_LONG).show();
			
			return;
			
			
		}
		
		
		 if(verifyLogin(userName,password).contains(">1"))
		{
			
			 progressBar1.setVisibility(View.GONE);
			mGetSavedData = "1";
			pref.edit().putString("savedData", mGetSavedData).commit();
			SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
			prefs.edit().putString("username", userName).commit();
			
			Toast.makeText(getApplicationContext(), "Login Successful...", Toast.LENGTH_LONG).show();
			Intent our2Intent=new Intent(MainActivity.this,MenuPage.class);
			 startActivity(our2Intent);
			 finish();
		}
		else
		{
			 progressBar1.setVisibility(View.GONE);
			 //lblStatus.setText("Login failed");
			 
			 Toast.makeText(getApplicationContext(), "UserName/Password does not match...", Toast.LENGTH_LONG).show();
			 
		}

		
	}
     // code to read the response from the web service
    public static String convertStreamToString(InputStream is) 
    {
    	BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    	StringBuilder sb = new StringBuilder();
    	String line = null;
    	try {
    		while ((line = reader.readLine()) != null) {
    			sb.append(line + "\n");
    		}
    	} 
    	catch (IOException e) {
    		e.printStackTrace();
    	} 
    	finally {
    		try {
    			is.close();
    		} catch (IOException e) {
				e.printStackTrace();
    		}
    	}
    	return sb.toString();
    }
    public static String verifyLogin(String UserName,String Password)
    {
    	try
    	{
    		 progressBar1.setVisibility(View.VISIBLE);
    		//System.out.println("guru");
    		DefaultHttpClient httpClient=new DefaultHttpClient();
    		//Connect to the server
    		HttpGet httpGet=new HttpGet(Constants.URL+"checkAdmin?username="+UserName+"&password="+Password);
    		//Get the response
    		HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
        	InputStream stream=httpEntity.getContent();
        	//Convert the stream to readable format
            String result= convertStreamToString(stream);
            Log.e("in the result methos", ""+result);
            
              return result.toString();
    	}
    	catch(Exception e)
    	{
    		return e.toString();
    	}
    }
    public void addKeyListener() {
    	 
    	// get edittext component
    	txtPassword = (EditText) findViewById(R.id.txtPassword);
     txtUserName=(EditText)findViewById(R.id.txtUserName);
    	// add a keylistener to keep track user input
    	txtPassword.setOnKeyListener(new OnKeyListener() {
    	public boolean onKey(View v, int keyCode, KeyEvent event) {
     
    		// if keydown and "enter" is pressed
    		if ((event.getAction() == KeyEvent.ACTION_DOWN)
    			&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
//     Toast.makeText(getApplicationContext(), "enter pressed", 20000).show();
    			// display a floating message
     click();
    			return true;
     
    		} else if ((event.getAction() == KeyEvent.ACTION_DOWN)
    			&& (keyCode == KeyEvent.KEYCODE_9)) {
    			
    			// display a floating message
    			
    			return true;
    		}
     
    		return false;
    	}
     });
    	txtUserName.setOnKeyListener(new OnKeyListener() {
        	public boolean onKey(View v, int keyCode, KeyEvent event) {
        	     
        		// if keydown and "enter" is pressed
        		if ((event.getAction() == KeyEvent.ACTION_DOWN)
        			&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
//         Toast.makeText(getApplicationContext(), "enter pressed", 20000).show();
        			// display a floating message
         click();
        			return true;
         
        		} else if ((event.getAction() == KeyEvent.ACTION_DOWN)
        			&& (keyCode == KeyEvent.KEYCODE_9)) {
        			
        			// display a floating message
        			
        			return true;
        		}
         
        		return false;
        	}
         });	
    }
}

	